package util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;

import static util.TokenHelper.SING;

@WebFilter(filterName = "FilterJWT",urlPatterns = {"/*"})
public class FilterJWT implements Filter {
  @Override
  public void destroy() {
  }

  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    System.out.println("Filter JWT - encoding begins");

    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)resp;

    //设置响应字符集
    response.setContentType("application/json;charset=UTF-8");
    //设置请求字符集
    request.setCharacterEncoding("UTF-8");

    String requestURI = request.getRequestURI();

    String token = request.getHeader("token");
    if (token==null){
      token = (String) request.getSession().getAttribute("token");
    }

    if(requestURI.contains("/login")){
      chain.doFilter(req,resp);
    }else {
      if(token != null){
        //响应前端
        JSONObject message = new JSONObject();
        Collection<String> collections = new LinkedList<>();
        try {
          //创建验证对象
          DecodedJWT verify =
                  JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
          //解码对象
          int size = verify.getClaims().size();
          for (int i = 1; i < size; i++) {
            collections.add(verify.getClaim(i+"").asString());
          }
          chain.doFilter(req,resp);
        } catch (Exception e) {
          message.put("message", "没有权限");
          response.getWriter().println(message);
        }
        message.put("用户",collections);
        response.getWriter().println(message);
      }
      System.out.println("Filter 1 - encoding ends");
    }
  }
  @Override
  public void init(FilterConfig config) throws ServletException {
  }
}
